import { useEffect, useState, useRef, memo } from "react"
import classNames from "classnames"
import styled from 'styled-components';
/**
 * LazyImage 
 * 图片懒加载组件
 */
const LazyImageStyled = styled.img`
    transition: all 1.3s ease-in;
    &.lazy-image{
         opacity: 0;
    }
    &.rendered{
         opacity: 1;
    }
    &.error{

    }
`
/**
 * LazyImage
 * @description 懒加载图片组件！
 * @returns React.Element
 */
const LazyImage = memo(function (props) {
    const { src, ...LazyProp } = props
    const imgRef = useRef()
    const [renderSrc, setRenderSrc] = useState('')
    /**
     * watchWeatherInView
     * @description 监听是否在视口中
     * @returns  void
     */
    const watchWeatherInView = () => {
        if (renderSrc||!imgRef.current) return
        const toViewTopPx = imgRef.current.getBoundingClientRect().top //距离视口上方的距离！
        const innerHeight = window.innerHeight//视口高度！
        console.log("scrolling")
        console.log(toViewTopPx<innerHeight)
        console.log(imgRef.current.offsetHeight)
        if (toViewTopPx+imgRef.current.offsetHeight < innerHeight) { //如果距离适口的距离小于或等于适口，则说明准备进入适口，或者已经进入了适口，则可以渲染！
            setRenderSrc(src)
            // document.removeEventListener("scroll", watchWeatherInView,true)
        }
    }
   function loadErr() {
        // imgRef.current.src = ""
   }
    const lazyImageClasses = classNames({
        "rendered": renderSrc,
    }, 'lazy-image')
    useEffect(() => {
        watchWeatherInView()
        //滚动事件冒泡到document上(清除监听事件也要清掉 监听options)
        document.addEventListener("scroll", watchWeatherInView, true)
        // useEffect 在渲染完成之后执行！
        return () => document.removeEventListener("scroll", watchWeatherInView,true)
    }, [renderSrc])
    return <LazyImageStyled className={lazyImageClasses} ref={imgRef} onError={loadErr} alt="图片异常" src={renderSrc} {...LazyProp} />
})

export default LazyImage;